import React, { useState } from 'react';  
import { Button } from 'antd';  
import { productOnline } from '../../api/axios8081';  
  
interface ApiResponse {  
  code: string;  
  date: null;  
  message: string;  
}  
  
const ProductActionButton: React.FC<{ productId: string, status: number }> = ({ productId, status }) => {  
  const [loading, setLoading] = useState(false);  
  const [error, setError] = useState(null);  
  
  const handleProductOnline = async () => {  
    setLoading(true);  
    setError(null);  
    try {  
      // 根据当前的status值动态设置要发送的请求status值  
      let requestStatus;  
      if (status === 4) {  
        requestStatus = 5;  
      } else if (status === 2) {  
        requestStatus = 4;  
      } else {  
        throw new Error('Invalid status value');  
      }  
  
      const response = await productOnline(productId, requestStatus) as unknown as ApiResponse;
       
      if (response.code === '0') {
        console.log(response.code)   
        alert('商品上下线操作成功！');  
      } else {  
        throw new Error(response.message);  
      }  
    } catch (err) {   
      
      alert('商品上下线操作成功！');  
    } finally {  
      setLoading(false);  
    }  
  };  
  
  const buttonText = status === 4 ? '下线' : '上线';  
  const isButtonDisabled = ![2,4].includes(status);  
  
  return (  
    <Button type="primary" loading={loading} onClick={handleProductOnline} disabled={isButtonDisabled} danger>  
      {buttonText}  
      {error && <span className="error-message">{error}</span>}  
    </Button>  
  );  
};  
  
export default ProductActionButton;